package com.sgb.kjwl.view.ui.fragment.home;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.google.android.material.tabs.TabLayout;
import com.sgb.alimaplibrary.util.ToastUtil;
import com.sgb.kjwl.AppLazyFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FrSearchNewBinding;
import com.sgb.kjwl.di.home.DaggerHomeFragComponent;
import com.sgb.kjwl.di.home.HomeFragModule;
import com.sgb.kjwl.model.entity.RecommendEntity;
import com.sgb.kjwl.model.entity.StoreEntity;
import com.sgb.kjwl.model.entity.home.SearchGoodsSummaryEntity;
import com.sgb.kjwl.model.entity.pick.PickSearchType;
import com.sgb.kjwl.view.ui.activity.home.SearchActivity5;
import com.sgb.kjwl.view.ui.activity.manage.WebsiteInfoActivity;
import com.sgb.kjwl.view.ui.activity.self.shop.ShopGoodsDetailActivity;
import com.sgb.kjwl.view.ui.adapter.home.SearchCompanyAdapter;
import com.sgb.kjwl.view.ui.adapter.home.SearchGoodsAdapter;
import com.sgb.kjwl.view.ui.adapter.home.SearchNewGoodsAdapter;
import com.sgb.kjwl.viewmodel.home.SearchNewFragModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.recyclerview.adapter.SlidingFragmentPagerAdapter;
import com.swgk.core.util.MToast;
import com.swgk.core.xrecyclerview.XRecyclerView;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

/*
 * 新搜索模块界面
 * liWei
 * */
public class SearchNewFragment extends AppLazyFragment {

    @Inject
    SearchNewFragModel viewModel;
    private FrSearchNewBinding binding;

    private String mSearchType;
    private String mKeyWord;

    private String[] menus;

    private int currentPage = 1;
    private String currentId = "";

    private SearchCompanyAdapter searchCompanyAdapter;  //企业
    //private SearchGoodsAdapter searchGoodsAdapter;  //商品
    private SearchNewGoodsAdapter searchNewGoodsAdapter;//新商品适配器
    private ArrayList<Fragment> mFragmentsRent = new ArrayList<>();
    private ArrayList<Fragment> mFragmentsCollect = new ArrayList<>();
    private ArrayList<Fragment> mFragmentsPick = new ArrayList<>();
    private boolean isRefresh = false;

    public static SearchNewFragment newInstance(String code) {
        SearchNewFragment fragment = new SearchNewFragment();
        Bundle bundle = new Bundle();
        bundle.putString("TYPE_SEARCH", code);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fr_search_new, container, false);
        return binding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerHomeFragComponent.builder()
                .appComponent(appComponent)
                .homeFragModule(new HomeFragModule(this))
                .build()
                .inject(this);
    }

    private void initFilterData(int page, boolean isLoadMore) {
        if (TextUtils.equals("goods", mSearchType) && !TextUtils.isEmpty(currentId)) {
            viewModel.searchGoodsList(mSearchType, mKeyWord, currentId, page, isLoadMore);
            return;
        }
        binding.rvTabLayout.setVisibility(View.VISIBLE);
        switch (mSearchType) {
            case "company":    //企业
                binding.rvTabLayout.setVisibility(View.GONE);
                viewModel.searchCompanyList(mSearchType, mKeyWord, page, isLoadMore);
                break;
            case "goods":     //商品
                viewModel.getGoodsSummary(mKeyWord);
                break;
            case "recruitment":    //招采
                viewModel.getPickSummary(mKeyWord);
                break;
            case "collect":   //集采
                viewModel.getXuFangCount(mKeyWord);
                break;
            case "rent":    //租赁
                viewModel.getLeaseHomeSearch("1", mKeyWord, 1);
                break;
        }
    }

    @Override
    protected void initView() {
        if (getArguments() != null) {
            mSearchType = getArguments().getString("TYPE_SEARCH");
        }
        binding.recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        binding.recyclerView.setPullRefreshEnabled(false);
        binding.recyclerView.setLoadingMoreEnabled(true);
        binding.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {

            }

            @Override
            public void onLoadMore() {
                currentPage = currentPage + 1;
                initFilterData(currentPage, true);
            }
        });
    }

    @Override
    protected void onLazyLoad() {
        if (getActivity() instanceof SearchActivity5){
            mKeyWord = ((SearchActivity5) getActivity()).getKeyWord();
        }
        initFilterData(currentPage, false);
    }

    @Override
    public void onVisible() {
        if (getActivity() instanceof SearchActivity5){
            String keyWord = ((SearchActivity5) getActivity()).getKeyWord();
            if (!TextUtils.equals(mKeyWord, keyWord)) {
                mKeyWord = keyWord;
                isRefresh = true;
                initFilterData(currentPage, false);
            }
        }

    }

    public void showCompanyList(List<StoreEntity> list, boolean isLoadMore, boolean isLast) {
        if (searchCompanyAdapter == null) {
            searchCompanyAdapter = new SearchCompanyAdapter(getActivity(), null);
            binding.recyclerView.removeAllViews();
            binding.recyclerView.setAdapter(searchCompanyAdapter);
        }
        searchCompanyAdapter.setOnItemClick(new AdapterOnItemClick<StoreEntity>() {
            @Override
            public void onItemClick(StoreEntity storeEntity, int position) {
                if (TextUtils.isEmpty(storeEntity.getNo())) {
                    ToastUtil.show(getActivity(), "企业店铺No不能为空");
                    return;
                }
                WebsiteInfoActivity.start(getActivity(), storeEntity.getNo(), WebsiteInfoActivity.WEBSITE_FOR_COMPANY, 0, 0);
            }
        });
        if (isLoadMore) {
            binding.recyclerView.loadMoreComplete();
            if (list != null && list.size() > 0) {
                searchCompanyAdapter.addDatas(list);
            }
            binding.recyclerView.setNoMore(isLast);
        } else {
            binding.recyclerView.refreshComplete();
            if (list != null && list.size() > 0) {
                binding.emptyView.setVisibility(View.GONE);
                searchCompanyAdapter.setDatas(list);
            } else {
                searchCompanyAdapter.clearDatas();
                binding.emptyView.setVisibility(View.VISIBLE);
            }
        }
    }

    public void setGoodsSummary(SearchGoodsSummaryEntity data) {
        if (data == null) {
            return;
        }
        if (isRefresh) {
            isRefresh = false;
            binding.rvTabLayout.removeAllTabs();
            List<SearchGoodsSummaryEntity.DataBean.CategoryBean> categoryBeanList = data.getDataBean().getCategory();
            if (categoryBeanList.size() == 0) {
                binding.rvTabLayout.addTab(binding.rvTabLayout.newTab().setText("全部"));
                return;
            }
            categoryBeanList.add(0, new SearchGoodsSummaryEntity.DataBean.CategoryBean("全部", "0"));
            menus = new String[categoryBeanList.size()];
            for (int i = 0; i < categoryBeanList.size(); i++) {
                if ("全部".equals(categoryBeanList.get(i).getName())) {
                    menus[i] = categoryBeanList.get(i).getName();
                } else {
                    menus[i] = categoryBeanList.get(i).getName() + "(" + categoryBeanList.get(i).getCount() + ")";
                }
                binding.rvTabLayout.addTab(binding.rvTabLayout.newTab().setText(menus[i]));
            }
            return;
        }
        binding.rvTabLayout.setVisibility(View.VISIBLE);
        binding.rvTabLayout.removeAllTabs();
        binding.rvTabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
        binding.rvTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                currentPage = 1;
                currentId = data.getDataBean().getCategory().get(tab.getPosition()).getId();
                initFilterData(currentPage, false);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        List<SearchGoodsSummaryEntity.DataBean.CategoryBean> categoryBeanList = data.getDataBean().getCategory();
        categoryBeanList.add(0, new SearchGoodsSummaryEntity.DataBean.CategoryBean("全部", "0"));
        menus = new String[categoryBeanList.size()];
        for (int i = 0; i < categoryBeanList.size(); i++) {
            if ("全部".equals(categoryBeanList.get(i).getName())) {
                menus[i] = categoryBeanList.get(i).getName();
            } else {
                menus[i] = categoryBeanList.get(i).getName() + "(" + categoryBeanList.get(i).getCount() + ")";
            }
            binding.rvTabLayout.addTab(binding.rvTabLayout.newTab().setText(menus[i]));
        }
    }

    public void showGoodsList(List<RecommendEntity> list, boolean isLoadMore, boolean isLast) {
        if (searchNewGoodsAdapter == null) {
            binding.recyclerView.setPadding(0,0, (int) getActivity().getResources().getDimension(R.dimen.dp10),0);
            binding.recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 2));
            searchNewGoodsAdapter = new SearchNewGoodsAdapter(getActivity(), null);
            binding.recyclerView.removeAllViews();
            binding.recyclerView.setAdapter(searchNewGoodsAdapter);
        }
        searchNewGoodsAdapter.setOnItemClick(new AdapterOnItemClick<RecommendEntity>() {
            @Override
            public void onItemClick(RecommendEntity recommendEntity, int position) {
                ShopGoodsDetailActivity.start(getActivity(), recommendEntity.getId(), "", recommendEntity.getSkuid());
            }
        });
        if (isLoadMore) {
            binding.recyclerView.loadMoreComplete();
            if (list != null && list.size() > 0) {
                searchNewGoodsAdapter.addDatas(list);
            }
            binding.recyclerView.setNoMore(isLast);
        } else {
            binding.recyclerView.refreshComplete();
            if (list != null && list.size() > 0) {
                binding.emptyView.setVisibility(View.GONE);
                searchNewGoodsAdapter.setDatas(list);
            } else {
                searchNewGoodsAdapter.clearDatas();
                binding.emptyView.setVisibility(View.VISIBLE);
            }
        }
    }

    public void showPickSummary(PickSearchType data) {
        if (data == null) {
            return;
        }
        menus = new String[3];
        menus[0] = "招采" + "(" + data.getTenderCount() + ")";
        menus[1] = "竞价" + "(" + data.getBidCount() + ")";
        menus[2] = "中标公告" + "(" + data.getBidNoticeCount() + ")";

        if (isRefresh) {
            isRefresh = false;
            binding.rvTabLayout.getTabAt(0).setText(menus[0]);
            binding.rvTabLayout.getTabAt(1).setText(menus[1]);
            binding.rvTabLayout.getTabAt(2).setText(menus[2]);
            Fragment fragmentPick = mFragmentsPick.get(binding.viewPager.getCurrentItem());
            ((SearchNewChildFragment) fragmentPick).refreshChildView(mSearchType, mKeyWord);
            return;
        }

        binding.rvTabLayout.setVisibility(View.VISIBLE);
        binding.rvTabLayout.removeAllTabs();
        binding.rvTabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
        mFragmentsPick.clear();
        mFragmentsPick.add(SearchNewChildFragment.newInstance(mSearchType, mKeyWord, 0));
        mFragmentsPick.add(SearchNewChildFragment.newInstance(mSearchType, mKeyWord, 1));
        mFragmentsPick.add(SearchNewChildFragment.newInstance(mSearchType, mKeyWord, 2));
        SlidingFragmentPagerAdapter adapter = new SlidingFragmentPagerAdapter(getChildFragmentManager(), mFragmentsPick, menus);
        binding.viewPager.setVisibility(View.VISIBLE);
        binding.viewPager.setAdapter(adapter);
        binding.viewPager.setOffscreenPageLimit(menus.length);
        binding.rvTabLayout.setupWithViewPager(binding.viewPager);
    }

    public void showCollectSummary(int common, int data) {
        menus = new String[2];
        menus[0] = "需方发起" + "(" + common + ")";
        menus[1] = "供方发起" + "(" + data + ")";

        if (isRefresh) {
            isRefresh = false;
            binding.rvTabLayout.getTabAt(0).setText(menus[0]);
            binding.rvTabLayout.getTabAt(1).setText(menus[1]);
            Fragment fragmentCollect = mFragmentsCollect.get(binding.viewPager.getCurrentItem());
            ((SearchNewChildFragment) fragmentCollect).refreshChildView(mSearchType, mKeyWord);
            return;
        }

        binding.rvTabLayout.setVisibility(View.VISIBLE);
        binding.rvTabLayout.removeAllTabs();
        binding.rvTabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
        mFragmentsCollect.clear();
        mFragmentsCollect.add(SearchNewChildFragment.newInstance(mSearchType, mKeyWord, 0));
        mFragmentsCollect.add(SearchNewChildFragment.newInstance(mSearchType, mKeyWord, 1));
        SlidingFragmentPagerAdapter adapter = new SlidingFragmentPagerAdapter(getChildFragmentManager(), mFragmentsCollect, menus);
        binding.viewPager.setVisibility(View.VISIBLE);
        binding.viewPager.setAdapter(adapter);
        binding.viewPager.setOffscreenPageLimit(menus.length);
        binding.rvTabLayout.setupWithViewPager(binding.viewPager);
    }

    public void getRentSummary(int common, int data) {
        if (menus == null) {
            menus = new String[2];
        }
        menus[0] = "出租信息" + "(" + common + ")";
        menus[1] = "求租信息" + "(" + data + ")";

        if (isRefresh) {
            isRefresh = false;
            binding.rvTabLayout.getTabAt(0).setText(menus[0]);
            binding.rvTabLayout.getTabAt(1).setText(menus[1]);
            Fragment fragmentRent = mFragmentsRent.get(binding.viewPager.getCurrentItem());
            ((SearchNewChildFragment) fragmentRent).refreshChildView(mSearchType, mKeyWord);
            return;
        }

        binding.rvTabLayout.setVisibility(View.VISIBLE);
        binding.rvTabLayout.removeAllTabs();
        binding.rvTabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
        mFragmentsRent.clear();
        mFragmentsRent.add(SearchNewChildFragment.newInstance(mSearchType, mKeyWord, 0));
        mFragmentsRent.add(SearchNewChildFragment.newInstance(mSearchType, mKeyWord, 1));
        SlidingFragmentPagerAdapter adapter = new SlidingFragmentPagerAdapter(getChildFragmentManager(), mFragmentsRent, menus);
        binding.viewPager.setVisibility(View.VISIBLE);
        binding.viewPager.setAdapter(adapter);
        binding.viewPager.setOffscreenPageLimit(menus.length);
        binding.rvTabLayout.setupWithViewPager(binding.viewPager);
    }

    public void refreshChildView() {
        if (getActivity() instanceof SearchActivity5){
            mKeyWord = ((SearchActivity5) getActivity()).getKeyWord();
        }
        isRefresh = true;
        if (currentId.equals("0")) {
            currentId = "";
        }
        switch (mSearchType) {
            case "company":    //企业
                binding.rvTabLayout.setVisibility(View.GONE);
                viewModel.searchCompanyList(mSearchType, mKeyWord, 1, false);
                break;
            case "goods":     //商品
                viewModel.getGoodsSummary(mKeyWord);
                viewModel.searchGoodsList(mSearchType, mKeyWord, currentId, 1, false);
                break;
            case "recruitment":    //招采
                viewModel.getPickSummary(mKeyWord);
                break;
            case "collect":   //集采
                viewModel.getXuFangCount(mKeyWord);
                break;
            case "rent":    //租赁
                viewModel.getLeaseHomeSearch("1", mKeyWord, 1);
                break;
        }
    }


}
